package com.lk.api.own;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.lk.api.R;

public class RemoteServiceTestActivity extends Activity {
	static final String TAG = "RemoteServiceTestActivity";
	public static final int SAY_HELLO_TO_CLIENT = 0;
	public Button mRemotStart, mRemotStopt;

	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub

			switch (msg.what) {
			case SAY_HELLO_TO_CLIENT:
				Toast.makeText(RemoteServiceTestActivity.this,
						"Hello World Remote Client!", Toast.LENGTH_SHORT)
						.show();
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}

	Messenger messenger_reciever = new Messenger(new IncomingHandler());



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.remoteservicetestactivity);

		mRemotStart = (Button) findViewById(R.id.StartRemoteBinder);
		mRemotStopt = (Button) findViewById(R.id.StopRemoteBinder);

		mRemotStart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.d(TAG, RemoteServiceTestActivity.this.getPackageCodePath());
				Intent service = new Intent(RemoteServiceTestActivity.this,
						RemoteService.class);
				bindService(service, connection, Context.BIND_AUTO_CREATE);
			}
		});
		mRemotStopt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				unbindService(connection);
			}
		});

	}

	ServiceConnection connection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Log.d(TAG, "service disconnected");
			connection.onServiceDisconnected(name);
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Log.d(TAG, "service connected");
			Messenger messenger = new Messenger(service);
			Message msg = new Message();
			msg.what = RemoteService.MSG_SAY_HELLO;
			msg.replyTo = messenger_reciever;

			try {
				messenger.send(msg);
			} catch (RemoteException e) {
				e.printStackTrace();
			}

		}
	};
}
